#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
策略模式 (Strategy Pattern) - Python实现详解

概述引导：
策略模式定义一系列算法，把它们一个个封装起来，并且使它们可相互替换。
策略模式让算法的变化独立于使用算法的客户。

学习要点：
1. 传统策略模式实现
2. 函数式策略模式
3. 装饰器策略模式
4. 动态策略选择

Java对比要点：
- Java需要定义策略接口和具体策略类
- Python可以直接使用函数作为策略
- Python支持动态策略注册
- Python的lambda表达式简化策略定义

关键理解：
策略模式消除条件语句，Python的函数式特性使实现更加简洁。
"""

from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional, Union, Protocol
from dataclasses import dataclass, field
from enum import Enum
from decimal import Decimal
import math
import time
import json
from functools import wraps, partial
import operator


# ============= 传统策略模式 =============

class PaymentStrategy(ABC):
    """
    支付策略抽象基类
    
    Java对比：
    - Java需要定义接口
    - Python使用ABC更灵活
    """
    
    @abstractmethod
    def pay(self, amount: Decimal) -> Dict[str, Any]:
        """执行支付"""
        pass
    
    @abstractmethod
    def validate(self, payment_info: Dict[str, Any]) -> bool:
        """验证支付信息"""
        pass
    
    @abstractmethod
    def get_fee(self, amount: Decimal) -> Decimal:
        """计算手续费"""
        pass


class CreditCardStrategy(PaymentStrategy):
    """
    信用卡支付策略
    """
    
    def __init__(self, card_number: str, cvv: str, expiry_date: str):
        self.card_number = card_number
        self.cvv = cvv
        self.expiry_date = expiry_date
        self.fee_rate = Decimal('0.025')  # 2.5%手续费
    
    def pay(self, amount: Decimal) -> Dict[str, Any]:
        """执行信用卡支付"""
        fee = self.get_fee(amount)
        total_amount = amount + fee
        
        # 模拟支付处理
        return {
            'method': 'credit_card',
            'amount': amount,
            'fee': fee,
            'total': total_amount,
            'card_last_four': self.card_number[-4:],
            'transaction_id': f'CC_{int(time.time())}',
            'status': 'success'
        }
    
    def validate(self, payment_info: Dict[str, Any]) -> bool:
        """验证信用卡信息"""
        # 简化的验证逻辑
        return (
            len(self.card_number) == 16 and
            len(self.cvv) == 3 and
            len(self.expiry_date) == 5
        )
    
    def get_fee(self, amount: Decimal) -> Decimal:
        """计算信用卡手续费"""
        return amount * self.fee_rate


class PayPalStrategy(PaymentStrategy):
    """
    PayPal支付策略
    """
    
    def __init__(self, email: str, password: str):
        self.email = email
        self.password = password
        self.fee_rate = Decimal('0.035')  # 3.5%手续费
    
    def pay(self, amount: Decimal) -> Dict[str, Any]:
        """执行PayPal支付"""
        fee = self.get_fee(amount)
        total_amount = amount + fee
        
        return {
            'method': 'paypal',
            'amount': amount,
            'fee': fee,
            'total': total_amount,
            'email': self.email,
            'transaction_id': f'PP_{int(time.time())}',
            'status': 'success'
        }
    
    def validate(self, payment_info: Dict[str, Any]) -> bool:
        """验证PayPal信息"""
        return '@' in self.email and len(self.password) >= 6
    
    def get_fee(self, amount: Decimal) -> Decimal:
        """计算PayPal手续费"""
        return amount * self.fee_rate


class BankTransferStrategy(PaymentStrategy):
    """
    银行转账支付策略
    """
    
    def __init__(self, account_number: str, routing_number: str):
        self.account_number = account_number
        self.routing_number = routing_number
        self.fixed_fee = Decimal('5.00')  # 固定手续费
    
    def pay(self, amount: Decimal) -> Dict[str, Any]:
        """执行银行转账"""
        fee = self.get_fee(amount)
        total_amount = amount + fee
        
        return {
            'method': 'bank_transfer',
            'amount': amount,
            'fee': fee,
            'total': total_amount,
            'account_last_four': self.account_number[-4:],
            'transaction_id': f'BT_{int(time.time())}',
            'status': 'pending'  # 银行转账通常需要时间
        }
    
    def validate(self, payment_info: Dict[str, Any]) -> bool:
        """验证银行账户信息"""
        return (
            len(self.account_number) >= 8 and
            len(self.routing_number) == 9
        )
    
    def get_fee(self, amount: Decimal) -> Decimal:
        """计算银行转账手续费"""
        return self.fixed_fee


class PaymentContext:
    """
    支付上下文类
    
    管理支付策略的使用
    """
    
    def __init__(self, strategy: PaymentStrategy = None):
        self._strategy = strategy
        self.payment_history: List[Dict[str, Any]] = []
    
    def set_strategy(self, strategy: PaymentStrategy):
        """设置支付策略"""
        self._strategy = strategy
    
    def execute_payment(self, amount: Decimal, payment_info: Dict[str, Any] = None) -> Dict[str, Any]:
        """执行支付"""
        if not self._strategy:
            raise ValueError("未设置支付策略")
        
        # 验证支付信息
        if not self._strategy.validate(payment_info or {}):
            return {
                'status': 'failed',
                'error': '支付信息验证失败'
            }
        
        # 执行支付
        result = self._strategy.pay(amount)
        
        # 记录支付历史
        self.payment_history.append({
            'timestamp': time.time(),
            'result': result
        })
        
        return result
    
    def get_payment_history(self) -> List[Dict[str, Any]]:
        """获取支付历史"""
        return self.payment_history.copy()


# ============= 函数式策略模式 =============

# 定义策略函数类型
SortStrategy = Callable[[List[Any]], List[Any]]
DiscountStrategy = Callable[[Decimal], Decimal]
ValidationStrategy = Callable[[str], bool]


# 排序策略函数
def bubble_sort(data: List[Any]) -> List[Any]:
    """冒泡排序策略"""
    result = data.copy()
    n = len(result)
    for i in range(n):
        for j in range(0, n - i - 1):
            if result[j] > result[j + 1]:
                result[j], result[j + 1] = result[j + 1], result[j]
    return result


def quick_sort(data: List[Any]) -> List[Any]:
    """快速排序策略"""
    if len(data) <= 1:
        return data.copy()
    
    pivot = data[len(data) // 2]
    left = [x for x in data if x < pivot]
    middle = [x for x in data if x == pivot]
    right = [x for x in data if x > pivot]
    
    return quick_sort(left) + middle + quick_sort(right)


def merge_sort(data: List[Any]) -> List[Any]:
    """归并排序策略"""
    if len(data) <= 1:
        return data.copy()
    
    mid = len(data) // 2
    left = merge_sort(data[:mid])
    right = merge_sort(data[mid:])
    
    result = []
    i = j = 0
    
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    
    result.extend(left[i:])
    result.extend(right[j:])
    return result


# 折扣策略函数
def no_discount(amount: Decimal) -> Decimal:
    """无折扣策略"""
    return Decimal('0')


def percentage_discount(rate: float) -> DiscountStrategy:
    """百分比折扣策略工厂"""
    def discount(amount: Decimal) -> Decimal:
        return amount * Decimal(str(rate))
    return discount


def fixed_discount(discount_amount: Decimal) -> DiscountStrategy:
    """固定金额折扣策略工厂"""
    def discount(amount: Decimal) -> Decimal:
        return min(discount_amount, amount)
    return discount


def tiered_discount(tiers: List[tuple]) -> DiscountStrategy:
    """阶梯折扣策略工厂"""
    def discount(amount: Decimal) -> Decimal:
        for min_amount, discount_rate in sorted(tiers, reverse=True):
            if amount >= Decimal(str(min_amount)):
                return amount * Decimal(str(discount_rate))
        return Decimal('0')
    return discount


# 验证策略函数
def email_validator(email: str) -> bool:
    """邮箱验证策略"""
    return '@' in email and '.' in email.split('@')[1]


def phone_validator(phone: str) -> bool:
    """手机号验证策略"""
    return phone.isdigit() and len(phone) == 11


def password_validator(password: str) -> bool:
    """密码验证策略"""
    return (
        len(password) >= 8 and
        any(c.isupper() for c in password) and
        any(c.islower() for c in password) and
        any(c.isdigit() for c in password)
    )


class FunctionalContext:
    """
    函数式策略上下文
    
    Python特色：
    - 直接使用函数作为策略
    - 更简洁的实现
    """
    
    def __init__(self):
        self.strategies: Dict[str, Callable] = {}
    
    def register_strategy(self, name: str, strategy: Callable):
        """注册策略函数"""
        self.strategies[name] = strategy
    
    def execute_strategy(self, name: str, *args, **kwargs) -> Any:
        """执行指定策略"""
        if name not in self.strategies:
            raise ValueError(f"未找到策略: {name}")
        
        return self.strategies[name](*args, **kwargs)
    
    def list_strategies(self) -> List[str]:
        """列出所有策略"""
        return list(self.strategies.keys())


# ============= 装饰器策略模式 =============

def strategy(name: str):
    """
    策略装饰器 - Python特色实现
    
    自动注册策略函数
    """
    def decorator(func: Callable):
        if not hasattr(strategy, 'registry'):
            strategy.registry = {}
        strategy.registry[name] = func
        return func
    return decorator


def get_strategy(name: str) -> Callable:
    """获取策略函数"""
    if not hasattr(strategy, 'registry'):
        raise ValueError("没有注册的策略")
    
    if name not in strategy.registry:
        raise ValueError(f"未找到策略: {name}")
    
    return strategy.registry[name]


def list_strategies() -> List[str]:
    """列出所有注册的策略"""
    if not hasattr(strategy, 'registry'):
        return []
    return list(strategy.registry.keys())


# 使用装饰器注册策略
@strategy('caesar_cipher')
def caesar_cipher(text: str, shift: int = 3) -> str:
    """凯撒密码加密策略"""
    result = ""
    for char in text:
        if char.isalpha():
            ascii_offset = 65 if char.isupper() else 97
            result += chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
        else:
            result += char
    return result


@strategy('base64_encode')
def base64_encode(text: str) -> str:
    """Base64编码策略"""
    import base64
    return base64.b64encode(text.encode()).decode()


@strategy('reverse_string')
def reverse_string(text: str) -> str:
    """字符串反转策略"""
    return text[::-1]


@strategy('rot13')
def rot13(text: str) -> str:
    """ROT13编码策略"""
    return text.encode('rot13')


# ============= 动态策略选择 =============

class StrategySelector:
    """
    动态策略选择器
    
    根据条件自动选择最佳策略
    """
    
    def __init__(self):
        self.strategies: Dict[str, Dict[str, Any]] = {}
        self.conditions: List[Callable] = []
    
    def register_strategy(self, name: str, strategy: Callable, 
                         priority: int = 0, condition: Callable = None):
        """注册策略"""
        self.strategies[name] = {
            'strategy': strategy,
            'priority': priority,
            'condition': condition or (lambda *args, **kwargs: True)
        }
    
    def select_strategy(self, *args, **kwargs) -> Optional[Callable]:
        """根据条件选择策略"""
        applicable_strategies = []
        
        for name, info in self.strategies.items():
            try:
                if info['condition'](*args, **kwargs):
                    applicable_strategies.append((name, info))
            except Exception:
                continue
        
        if not applicable_strategies:
            return None
        
        # 按优先级排序，选择最高优先级的策略
        applicable_strategies.sort(key=lambda x: x[1]['priority'], reverse=True)
        return applicable_strategies[0][1]['strategy']
    
    def execute_best_strategy(self, *args, **kwargs) -> Any:
        """执行最佳策略"""
        strategy = self.select_strategy(*args, **kwargs)
        if not strategy:
            raise ValueError("没有适用的策略")
        
        return strategy(*args, **kwargs)


# ============= 实际应用示例 =============

class ShoppingCart:
    """
    购物车类 - 策略模式应用示例
    
    使用策略模式处理不同的折扣计算
    """
    
    def __init__(self):
        self.items: List[Dict[str, Any]] = []
        self.discount_strategy: DiscountStrategy = no_discount
    
    def add_item(self, name: str, price: Decimal, quantity: int = 1):
        """添加商品"""
        self.items.append({
            'name': name,
            'price': price,
            'quantity': quantity,
            'subtotal': price * quantity
        })
    
    def set_discount_strategy(self, strategy: DiscountStrategy):
        """设置折扣策略"""
        self.discount_strategy = strategy
    
    def calculate_total(self) -> Dict[str, Decimal]:
        """计算总价"""
        subtotal = sum(item['subtotal'] for item in self.items)
        discount = self.discount_strategy(subtotal)
        total = subtotal - discount
        
        return {
            'subtotal': subtotal,
            'discount': discount,
            'total': total
        }
    
    def get_items(self) -> List[Dict[str, Any]]:
        """获取商品列表"""
        return self.items.copy()


class DataProcessor:
    """
    数据处理器 - 策略模式应用示例
    
    使用策略模式处理不同的排序算法
    """
    
    def __init__(self):
        self.sort_strategy: SortStrategy = sorted  # 默认使用内置排序
    
    def set_sort_strategy(self, strategy: SortStrategy):
        """设置排序策略"""
        self.sort_strategy = strategy
    
    def process_data(self, data: List[Any]) -> Dict[str, Any]:
        """处理数据"""
        start_time = time.time()
        sorted_data = self.sort_strategy(data)
        end_time = time.time()
        
        return {
            'original_data': data,
            'sorted_data': sorted_data,
            'processing_time': end_time - start_time,
            'data_size': len(data)
        }


# ============= 演示函数 =============

def demonstrate_traditional_strategy():
    """
    演示传统策略模式
    
    概述引导：
    展示传统策略模式的实现，包括策略接口、具体策略类
    和上下文类的使用。
    
    学习要点：
    1. 策略接口的定义
    2. 具体策略的实现
    3. 上下文类的管理
    4. 策略的动态切换
    
    关键理解：
    策略模式将算法封装成独立的类，便于扩展和维护。
    """
    print("=== 传统策略模式演示 ===")
    print("\n学习目标：")
    print("- 理解策略模式的结构")
    print("- 掌握策略的封装和切换")
    print("- 学习算法族的管理")
    print("\n重点概念：")
    print("- 算法的封装")
    print("- 策略的可替换性")
    print("- 开闭原则的应用")
    print("=" * 50)
    
    # 创建支付上下文
    payment_context = PaymentContext()
    
    # 测试不同的支付策略
    amount = Decimal('100.00')
    
    print(f"\n支付金额: ¥{amount}")
    
    # 信用卡支付
    print("\n=== 信用卡支付 ===")
    credit_card = CreditCardStrategy("1234567890123456", "123", "12/25")
    payment_context.set_strategy(credit_card)
    result = payment_context.execute_payment(amount)
    print(f"支付结果: {json.dumps(result, indent=2, default=str)}")
    
    # PayPal支付
    print("\n=== PayPal支付 ===")
    paypal = PayPalStrategy("user@example.com", "password123")
    payment_context.set_strategy(paypal)
    result = payment_context.execute_payment(amount)
    print(f"支付结果: {json.dumps(result, indent=2, default=str)}")
    
    # 银行转账
    print("\n=== 银行转账 ===")
    bank_transfer = BankTransferStrategy("12345678901", "123456789")
    payment_context.set_strategy(bank_transfer)
    result = payment_context.execute_payment(amount)
    print(f"支付结果: {json.dumps(result, indent=2, default=str)}")
    
    # 查看支付历史
    print(f"\n支付历史记录数: {len(payment_context.get_payment_history())}")


def demonstrate_functional_strategy():
    """
    演示函数式策略模式
    """
    print("\n=== 函数式策略模式演示 ===")
    
    # 创建函数式上下文
    context = FunctionalContext()
    
    # 注册排序策略
    context.register_strategy('bubble_sort', bubble_sort)
    context.register_strategy('quick_sort', quick_sort)
    context.register_strategy('merge_sort', merge_sort)
    context.register_strategy('python_sort', sorted)
    
    # 注册折扣策略
    context.register_strategy('no_discount', no_discount)
    context.register_strategy('vip_discount', percentage_discount(0.1))  # 10%折扣
    context.register_strategy('bulk_discount', fixed_discount(Decimal('20')))
    context.register_strategy('tiered_discount', tiered_discount([
        (100, 0.05),  # 满100享5%折扣
        (500, 0.1),   # 满500享10%折扣
        (1000, 0.15)  # 满1000享15%折扣
    ]))
    
    print(f"\n注册的策略: {context.list_strategies()}")
    
    # 测试排序策略
    test_data = [64, 34, 25, 12, 22, 11, 90]
    print(f"\n原始数据: {test_data}")
    
    for sort_name in ['bubble_sort', 'quick_sort', 'merge_sort', 'python_sort']:
        sorted_data = context.execute_strategy(sort_name, test_data)
        print(f"{sort_name}: {sorted_data}")
    
    # 测试折扣策略
    test_amounts = [Decimal('50'), Decimal('150'), Decimal('600'), Decimal('1200')]
    
    print("\n=== 折扣策略测试 ===")
    for amount in test_amounts:
        print(f"\n金额: ¥{amount}")
        for discount_name in ['no_discount', 'vip_discount', 'bulk_discount', 'tiered_discount']:
            discount = context.execute_strategy(discount_name, amount)
            final_amount = amount - discount
            print(f"  {discount_name}: 折扣¥{discount}, 实付¥{final_amount}")


def demonstrate_decorator_strategy():
    """
    演示装饰器策略模式
    """
    print("\n=== 装饰器策略模式演示 ===")
    
    print(f"\n注册的策略: {list_strategies()}")
    
    # 测试文本处理策略
    test_text = "Hello World! This is a test message."
    print(f"\n原始文本: {test_text}")
    
    for strategy_name in list_strategies():
        try:
            strategy_func = get_strategy(strategy_name)
            if strategy_name == 'caesar_cipher':
                result = strategy_func(test_text, 5)
            else:
                result = strategy_func(test_text)
            print(f"{strategy_name}: {result}")
        except Exception as e:
            print(f"{strategy_name}: 执行失败 - {e}")


def demonstrate_dynamic_strategy():
    """
    演示动态策略选择
    """
    print("\n=== 动态策略选择演示 ===")
    
    selector = StrategySelector()
    
    # 注册不同数据大小的排序策略
    selector.register_strategy(
        'small_data_sort',
        bubble_sort,
        priority=1,
        condition=lambda data: len(data) <= 10
    )
    
    selector.register_strategy(
        'medium_data_sort',
        quick_sort,
        priority=2,
        condition=lambda data: 10 < len(data) <= 100
    )
    
    selector.register_strategy(
        'large_data_sort',
        merge_sort,
        priority=3,
        condition=lambda data: len(data) > 100
    )
    
    # 测试不同大小的数据
    test_cases = [
        [3, 1, 4, 1, 5],  # 小数据
        list(range(50, 0, -1)),  # 中等数据
        list(range(200, 0, -1))  # 大数据
    ]
    
    for i, data in enumerate(test_cases):
        print(f"\n测试案例 {i+1} (数据大小: {len(data)}):")
        selected_strategy = selector.select_strategy(data)
        if selected_strategy:
            start_time = time.time()
            result = selected_strategy(data)
            end_time = time.time()
            print(f"选择的策略: {selected_strategy.__name__}")
            print(f"排序时间: {end_time - start_time:.6f}秒")
            print(f"结果正确: {result == sorted(data)}")
        else:
            print("没有找到适用的策略")


def demonstrate_shopping_cart():
    """
    演示购物车应用
    """
    print("\n=== 购物车策略应用演示 ===")
    
    cart = ShoppingCart()
    
    # 添加商品
    cart.add_item("笔记本电脑", Decimal('5999'), 1)
    cart.add_item("鼠标", Decimal('99'), 2)
    cart.add_item("键盘", Decimal('299'), 1)
    
    print("\n购物车商品:")
    for item in cart.get_items():
        print(f"  {item['name']}: ¥{item['price']} x {item['quantity']} = ¥{item['subtotal']}")
    
    # 测试不同折扣策略
    strategies = [
        ("无折扣", no_discount),
        ("VIP折扣(10%)", percentage_discount(0.1)),
        ("满减优惠(减100)", fixed_discount(Decimal('100'))),
        ("阶梯折扣", tiered_discount([
            (1000, 0.05),
            (5000, 0.1),
            (10000, 0.15)
        ]))
    ]
    
    print("\n=== 不同折扣策略对比 ===")
    for name, strategy in strategies:
        cart.set_discount_strategy(strategy)
        total_info = cart.calculate_total()
        print(f"\n{name}:")
        print(f"  小计: ¥{total_info['subtotal']}")
        print(f"  折扣: ¥{total_info['discount']}")
        print(f"  总计: ¥{total_info['total']}")


def demonstrate_java_comparison():
    """
    Java对比演示
    
    Java等价代码：
    ```java
    // Java版本的策略模式
    public interface PaymentStrategy {
        PaymentResult pay(BigDecimal amount);
        boolean validate(PaymentInfo info);
        BigDecimal getFee(BigDecimal amount);
    }
    
    public class CreditCardStrategy implements PaymentStrategy {
        private String cardNumber;
        private String cvv;
        private String expiryDate;
        
        @Override
        public PaymentResult pay(BigDecimal amount) {
            // 实现信用卡支付逻辑
            return new PaymentResult("success", amount);
        }
        
        @Override
        public boolean validate(PaymentInfo info) {
            // 验证逻辑
            return true;
        }
        
        @Override
        public BigDecimal getFee(BigDecimal amount) {
            return amount.multiply(new BigDecimal("0.025"));
        }
    }
    
    public class PaymentContext {
        private PaymentStrategy strategy;
        
        public void setStrategy(PaymentStrategy strategy) {
            this.strategy = strategy;
        }
        
        public PaymentResult executePayment(BigDecimal amount) {
            return strategy.pay(amount);
        }
    }
    
    // 使用
    PaymentContext context = new PaymentContext();
    context.setStrategy(new CreditCardStrategy("1234", "123", "12/25"));
    PaymentResult result = context.executePayment(new BigDecimal("100.00"));
    ```
    
    Python优势：
    1. 函数可以直接作为策略
    2. 装饰器简化策略注册
    3. 动态策略选择更灵活
    4. Lambda表达式简化策略定义
    """
    print("\n=== Java对比说明 ===")
    print("\nPython优势：")
    print("1. 函数可以直接作为策略")
    print("2. 装饰器简化策略注册")
    print("3. 动态策略选择更灵活")
    print("4. Lambda表达式简化策略定义")
    print("5. 更少的样板代码")
    
    print("\nJava特点：")
    print("1. 强类型的策略接口")
    print("2. 编译时类型检查")
    print("3. 更明确的契约定义")
    print("4. IDE支持更好")
    
    # 演示Python的函数式优势
    print("\n=== Python函数式优势演示 ===")
    
    # 使用lambda作为策略
    strategies = {
        'double': lambda x: x * 2,
        'square': lambda x: x ** 2,
        'cube': lambda x: x ** 3,
        'factorial': lambda x: math.factorial(x) if x >= 0 else 0
    }
    
    test_value = 5
    print(f"\n测试值: {test_value}")
    for name, strategy in strategies.items():
        try:
            result = strategy(test_value)
            print(f"{name}: {result}")
        except Exception as e:
            print(f"{name}: 错误 - {e}")


def performance_comparison():
    """
    性能对比测试
    """
    print("\n=== 性能对比 ===")
    
    # 创建测试数据
    test_data = list(range(1000, 0, -1))
    
    # 测试不同排序策略的性能
    strategies = {
        'Python内置排序': sorted,
        '快速排序': quick_sort,
        '归并排序': merge_sort
    }
    
    print(f"\n数据大小: {len(test_data)}")
    print("排序性能对比:")
    
    for name, strategy in strategies.items():
        start_time = time.time()
        result = strategy(test_data)
        end_time = time.time()
        
        is_correct = result == sorted(test_data)
        print(f"{name}: {end_time - start_time:.6f}秒, 正确性: {is_correct}")
    
    # 测试策略切换的开销
    print("\n策略切换开销测试:")
    
    context = FunctionalContext()
    context.register_strategy('test_strategy', lambda x: x * 2)
    
    # 测试直接调用
    start_time = time.time()
    for i in range(10000):
        result = test_data[0] * 2
    direct_time = time.time() - start_time
    
    # 测试通过策略调用
    start_time = time.time()
    for i in range(10000):
        result = context.execute_strategy('test_strategy', test_data[0])
    strategy_time = time.time() - start_time
    
    print(f"直接调用 (10000次): {direct_time:.6f}秒")
    print(f"策略调用 (10000次): {strategy_time:.6f}秒")
    print(f"开销比例: {strategy_time / direct_time:.2f}x")


def main():
    """主函数"""
    demonstrate_traditional_strategy()
    demonstrate_functional_strategy()
    demonstrate_decorator_strategy()
    demonstrate_dynamic_strategy()
    demonstrate_shopping_cart()
    demonstrate_java_comparison()
    performance_comparison()


if __name__ == "__main__":
    main()